package com.ipzoe.web.core.i18n;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 从cookie中获取语言
 * @author zhangmingming
 */
public class LocaleFromCookieInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String newLocale = I18nUtil.getLocaleFromCookie(request);

        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if (localeResolver == null) {
            throw new IllegalStateException(
                    "No LocaleResolver found: not in a DispatcherServlet request?");
        }
        try {
            localeResolver.setLocale(request, response, parseLocaleValue(newLocale));
        } catch (IllegalArgumentException ex) {
            localeResolver.setLocale(request, response, Locale.SIMPLIFIED_CHINESE);
        }
        return super.preHandle(request, response, handler);
    }

    protected static Locale parseLocaleValue(String localeValue) {
        return StringUtils.parseLocale(localeValue);
    }

}
